import React, { useState, useEffect } from 'react';
import './AI-Factors.scss';
import { Card, Button, Input, Table, Tag, Progress, Divider, message } from 'antd';
import { RobotOutlined, SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import { Bar } from '@ant-design/charts';
import axios from 'axios';
import { fetchMarketData } from '../../../api/AIApi'; // 假设你有一个API文件来获取市场数据

const AIFactors = () => {
  const [loading, setLoading] = useState(false);
  const [marketData, setMarketData] = useState([]);
  const [resultsVisible, setResultsVisible] = useState(false);
  const [factorResult, setFactorResult] = useState(null);
  const [selectedStocks, setSelectedStocks] = useState([]);

  // 数据获取函数
  let amt = 5;
  // const fetchMarketData = async () => {
  //   const token = localStorage.getItem("jwt_token");
  //   let allStocks = [];
  //   try {
  //     for (let page = 1; page <= amt; page++) {
  //       const res = await axios.get(`/api/ui/stocklist?page=${page}`, {
  //         headers: { Authorization: `Bearer ${token}` },
  //       });
  //       console.log(`第 ${page} 页数据:`, res.data);
  //       if (res.data.code === 0) {
  //         const stocksPage = res.data.data.map(stock => ({
  //           股票代码: stock.股票代码,
  //           股票名称: stock.股票名称,
  //           最新价: stock.最新价,
  //           涨跌幅: stock.涨跌幅,
  //           涨跌额: stock.涨跌额,
  //           成交量: stock.成交量,
  //           振幅: stock.振幅,
  //           最高: stock.最高,
  //           最低: stock.最低,
  //           今开: stock.今开,
  //           昨收: stock.昨收,
  //           市盈率: stock.市盈率,
  //           换手率: stock.换手率
  //         }));
  //         allStocks = [...allStocks, ...stocksPage];
  //       }
  //     }
  //     setMarketData(allStocks);
  //     return allStocks;
  //   } catch (error) {
  //     console.error("获取市场数据失败:", error);
  //     message.error("获取市场数据失败，请稍后重试");
  //     return [];
  //   }
  // };

  useEffect(() => {
    const tempMarketData = []; // 创建临时数组
    fetchMarketData(1, tempMarketData).then(() => {
      if (tempMarketData.length === 0) {
        message.warning("未获取到任何股票数据，请检查网络连接或稍后重试");
      } else {
        setMarketData(tempMarketData); // 更新状态
        // 本地存储市场数据
        localStorage.setItem("market_data", JSON.stringify(tempMarketData));
        setSelectedStocks(tempMarketData.slice(0, 10));
      }
    });
  }, []);

  // 根据因子分析结果的返回情况，用useEffect来更新结果可见性
  useEffect(() => {
    if (factorResult && factorResult.factors && factorResult.factors.length > 0) {
      setResultsVisible(true);
      // 在浏览器缓存存储股票信息
      localStorage.setItem("factors", JSON.stringify(factorResult));
      console.log("因子分析结果已保存到本地缓存:", factorResult);
    
    } else {
      setResultsVisible(false);
    }
  }, [factorResult]);

  const handleAnalyze = async () => {
  setLoading(true);
  try {
    const token = localStorage.getItem("jwt_token");

    
    const requestPayload = JSON.stringify({ market_data: marketData });
    console.log("请求体:", requestPayload);

    const response = await axios.post(
      "/api/data/factor",
      requestPayload,
      {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      }
    );
    console.log("因子分析响应:", response.data);

    // 保存完整结果
    const { factors, summary } = response.data.data;
    setFactorResult({ factors, summary });

    setResultsVisible(true);
    setLoading(false);
    message.success("因子分析完成");
  } catch (error) {
    console.error("因子分析失败:", error);
    message.error("因子分析失败，请检查输入数据");
    setLoading(false);
  }
};

  // const factorChartConfig = {
  //   data: factorResult?.factors.map(f => ({
  //     factor: f.name,
  //     weight: f.weight,
  //     direction: f.impact > 0 ? '正向' : '负向',
  //   })) || [],
  //   xField: 'weight',
  //   yField: 'factor',
  //   seriesField: 'direction',
  //   legend: false,
  //   color: ({ direction }) => (direction === '正向' ? '#52c41a' : '#f5222d'),
  //   height: 300,
  // };

  const tableColumns = [
    {
      title: '因子名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <b>{text}</b>,
    },
    {
      title: '资产类别',
      dataIndex: 'asset_class',
      key: 'asset_class',
    },
    {
      title: '影响方向',
      dataIndex: 'impact',
      key: 'impact',
      render: (value) => value === 1 ? <Tag color="green">正面</Tag> : <Tag color="red">负面</Tag>,
    },
    {
      title: '影响强度',
      dataIndex: 'intensity',
      key: 'intensity',
      render: (value) => '⭐'.repeat(value),
    },
    {
      title: '佐证语句',
      dataIndex: 'evidence',
      key: 'evidence',
    },
  ];

  return (
    <div className="ai-factors-page">
      <Card title={<><RobotOutlined /> 智能因子挖掘引擎</>} bordered={false} className="glass-card">
        <p>利用 AI 助手基于大模型进行多因子分析，提取投资逻辑</p>
        <Divider />
        <div className="main-section">
          <div className="left-panel">
            <Card title="股票市场数据 (JSON 数组)" size="small">
              <Input.TextArea
                rows={6}
                placeholder="如果你有相关知识，请输入市场数据（JSON）。否则Manbo助手将自动获取市场数据。"
                onChange={(e) => {
                  try {
                    setMarketData(JSON.parse(e.target.value));
                  } catch {
                    setMarketData([]);
                  }
                }}
              />
            </Card>
          </div>
          <div className="right-panel">
            {loading && (
              <div className="analyzing">
                <Progress percent={70} status="active" showInfo={false} />
                <p>🤖 DeepSeek助手：正在分析关键因子，请稍候...</p>
                
              </div>
              
              
            )}
            {resultsVisible && (
              <>
                {/* <Card title="因子重要性分析" size="small">
                  
                  <Bar {...factorChartConfig} />
                </Card> */}
                <Card title="因子分析结果" size="small" style={{ marginTop: '16px' }}>
                  <Table
                   
                    dataSource={factorResult.factors.map((item, index) => ({
                      key: index,
                      ...item,
                    }))}
                    columns={tableColumns}
                    pagination={false}
                    bordered
                  />
                </Card>
              </>
            )}
          </div>
        </div>
        <Divider />
        <div className="button-section">
          <Button type="primary" onClick={handleAnalyze} loading={loading} icon={<SearchOutlined />}>进行因子分析</Button>
        </div>
      </Card>
    </div>
  );
};

export default AIFactors;
